//
//  LLine.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 8/16/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "LLine.h"
#import "Utility.h"
#import "DefineXML.h"


@implementation LLine
@synthesize _state = mState;

-(id) initWithNode:(LNode *)node
{
    if (self = [super initWithSpriteFrameName:[self getSpriteFrameName]])
    {
        mNode = node;
        
        [self setIsUseBox2xAnchorPoint:NO];
        [self setAnchorPoint:ccp(0.5f, 0.0f)];
        [self createBody];
        [self updateLine];
        [self schedule:@selector(updateLine)];
        
        CCAction *anim = [[Utility getInstance] getAnimWithKey:XML_ANIM_LAZER delay:0.1 loop:0];
        [self runAction:anim];
    }
    
    return self;
}

-(void) createBody
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0, 0);
    
    _b2Body = PhysicSystem::getInstance()->mWorld->CreateBody(&bodyDef);
    
    CGPoint sub = ccpSub([mNode._nextNode getRealPosition], [mNode getRealPosition]);
    b2EdgeShape shape;
    shape.Set(b2Vec2(0, 0), b2Vec2(0, ccpLength(sub) / PTM_RATIO));
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.filter.categoryBits = [self getObjectType];
    fixtureDef.filter.maskBits = MASK_BIT_LAZER_LINE;
    fixtureDef.isSensor = true;
    _b2Body->CreateFixture(&fixtureDef);
    
    [self setPTMRatio:PTM_RATIO];
    _b2Body->SetUserData(self);
}

-(void) updateLine
{
    CGPoint sub = ccpSub([mNode._nextNode getRealPosition], [mNode getRealPosition]);
    float length = ccpLength(sub);
    [self setPosition:[mNode getRealPosition]];
    [self setScaleY:(length / self.contentSize.height)];
    [self setRotation:[[Utility getInstance] vectorToAngle:sub]];
    
    _b2Body->DestroyFixture(_b2Body->GetFixtureList());
    b2EdgeShape shape;
    shape.Set(b2Vec2(0, 0), b2Vec2(0, length / PTM_RATIO));
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.filter.categoryBits = [self getObjectType];
    fixtureDef.filter.maskBits = MASK_BIT_LAZER_LINE;
    fixtureDef.isSensor = true;
    _b2Body->CreateFixture(&fixtureDef);
}

-(void) on
{
    [self setVisible:YES];
    mState = eLLS_ON;
}

-(void) off
{
    [self setVisible:NO];
    mState = eLLS_OFF;
}

-(OBJECT_TYPE) getObjectType
{
    return eO_LAZER_LINE;
}

-(NSString *) getSpriteFrameName
{
    return SFN_LLINE;
}

-(void) dealloc
{
    [super dealloc];
    CCLOG(@"LLine dealloc!");
}

@end
